package cn.appsys.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.service.appinfo.DevAppService;
import cn.appsys.service.categoary.DevCatService;
import cn.appsys.service.data.DevDataService;
import cn.appsys.service.version.DevVerService;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;




@Controller
@RequestMapping("/dev/flatform")
public class DevAppController {
private Logger logger = Logger.getLogger(DevAppController.class);
	
	@Resource
	private DevAppService devAppService;
	@Resource
	private DevDataService devDatService;
	@Resource
	private DevVerService devVerService;
	@Resource
	private DevCatService devCatService;
	
	@RequestMapping(value="/app/list")
	public String getAppInfoList(Model model,HttpSession session,
            @RequestParam(value="querySoftwareName",required=false)String querySoftwareName,
            @RequestParam(value="queryStatus",required=false)String _queryStatus,
            @RequestParam(value="queryFlatformId",required=false) String _queryFlatformId,
            @RequestParam(value="queryCategoryLevel1",required=false) String _queryCategoryLevel1,
            @RequestParam(value="queryCategoryLevel2",required=false) String _queryCategoryLevel2,
            @RequestParam(value="queryCategoryLevel3",required=false) String _queryCategoryLevel3,
            @RequestParam(value="pageIndex",required=false) String pageIndex ){
		logger.info("getAppInfoList ---- > querySoftwareName: " + querySoftwareName);
		logger.info("getAppInfoList ---- > queryStatus: " + _queryStatus);
		logger.info("getAppInfoList ---- > queryFlatformId: " + _queryFlatformId);
		logger.info("getAppInfoList ---- > queryCategoryLevel1: " + _queryCategoryLevel1);
		logger.info("getAppInfoList ---- > queryCategoryLevel2: " + _queryCategoryLevel2);
		logger.info("getAppInfoList ---- > queryCategoryLevel3: " + _queryCategoryLevel3);
		logger.info("getAppInfoList ---- > pageIndex: " + pageIndex);
//		Integer _queryInfoVer = null;	
		List<AppInfo> appInfoList=null;
		List<DataDictionary> statusList=null;
		List<DataDictionary> flatFormList=null;
		List<AppCategory> categoryLevel1List=null;
		List<AppCategory> categoryLevel2List=null;
		List<AppCategory> categoryLevel3List=null;
//		List<AppVersion> appVersion = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
    	
    	Integer devId=null;
		Integer queryStatus=null;
		Integer queryFlatformId=null;
		Integer queryCategoryLevel1=null;
		Integer queryCategoryLevel2=null;
		Integer queryCategoryLevel3=null;
	
		if(querySoftwareName == null){
			querySoftwareName = "";
		}
		if(_queryStatus!= null && !_queryStatus.equals("")){
			queryStatus = Integer.parseInt(_queryStatus);
		}
		if(_queryFlatformId!= null && !_queryFlatformId.equals("")){
			queryFlatformId = Integer.parseInt(_queryFlatformId);
		}
		if(_queryCategoryLevel1!= null && !_queryCategoryLevel1.equals("")){
			queryCategoryLevel1 = Integer.parseInt(_queryCategoryLevel1);
		}
		if(_queryCategoryLevel2!= null && !_queryCategoryLevel2.equals("")){
			queryCategoryLevel2 = Integer.parseInt(_queryCategoryLevel2);
		}
		if(_queryCategoryLevel3!= null && !_queryCategoryLevel3.equals("")){
			queryCategoryLevel3 = Integer.parseInt(_queryCategoryLevel3);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			return "redirect:/syserror.html";
    		}
    	}	
    	//总数量（表）	
    	int totalCount = 0;
		try {
			totalCount = devAppService.getAppInfoCount(querySoftwareName,queryStatus,queryFlatformId,queryCategoryLevel1,
					queryCategoryLevel2,queryCategoryLevel3, totalCount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	int totalPageCount = pages.getTotalPageCount();
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		try {
			appInfoList=devAppService.getAppInfoList(querySoftwareName, queryStatus, devId,
                    queryFlatformId, queryCategoryLevel1, 
                    queryCategoryLevel2, queryCategoryLevel3, 
                    currentPageNo, pageSize);
			statusList = devDatService.getDataList("APP_STATUS");
			flatFormList = devDatService.getDataList("APP_FLATFORM");
			categoryLevel1List = devCatService.getAppCategoryByparentId(null);
//			categoryLevel2List = devCatService.getAppCategoryByparentId(null);
//			categoryLevel3List = devCatService.getAppCategoryByparentId(null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addAttribute("appInfoList",appInfoList);
		model.addAttribute("statusList",statusList);
		model.addAttribute("flatFormList",flatFormList);
		model.addAttribute("categoryLevel1List",categoryLevel1List);
		model.addAttribute("categoryLevel2List",categoryLevel2List);
		model.addAttribute("categoryLevel3List",categoryLevel3List);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pages",pages);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("querySoftwareName",querySoftwareName);
		model.addAttribute("queryStatus",queryStatus);
		model.addAttribute("queryStatus",queryStatus);
		model.addAttribute("queryCategoryLevel1",queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2",queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3",queryCategoryLevel3);
		
		return "developer/appinfolist";
	}
	
	@RequestMapping("/app/categorylevellist")
	@ResponseBody	
	public List<AppCategory> getCategoryList(@RequestParam(value="pid",required=false)Integer pid)
	{
		List<AppCategory> list=new ArrayList<AppCategory>();
		try {
			list= devCatService.getAppCategoryByparentId(pid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	@RequestMapping(value="/app/datadictionarylist",method=RequestMethod.GET)
	@ResponseBody
	public List<DataDictionary> getDataDictionaryList (@RequestParam (value="tcode",required=false)String tcode){
		List<DataDictionary> list=new ArrayList<DataDictionary>();
		try {
			list=devDatService.getDataList(tcode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	//添加
		@RequestMapping(value="/appinfo/appinfoadd",method=RequestMethod.GET)
		public String addAppInfo(@ModelAttribute("appInfo") AppInfo appInfo){
			return "developer/appinfoadd";
		}
		
		//查看
		@RequestMapping(value="/app/appview/{id}",method=RequestMethod.GET)
		public String view(@PathVariable String id,Model model,HttpServletRequest request){
			logger.debug("view id===================== "+id);
			AppInfo appInfo=new AppInfo();
			try {
				appInfo = devAppService.getAppInfoById(Integer.parseInt(id));
				if(appInfo.getLogoLocPath() != null && !"".equals(appInfo.getLogoLocPath())){
					String[] paths = appInfo.getLogoLocPath().split("\\"+File.separator);
					logger.debug("view picPath paths[paths.length-1]============ " + paths[paths.length-1]);
					appInfo.setLogoLocPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
				}
				if(appInfo.getLogoPicPath() != null && !"".equals(appInfo.getLogoPicPath())){
					String[] paths = appInfo.getLogoPicPath().split("\\"+File.separator);
					logger.debug("view workPicPath paths[paths.length-1]============ " + paths[paths.length-1]);
					appInfo.setLogoPicPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
				}
				
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			model.addAttribute(appInfo);
			return "developer/appinfoview";
		}
		//删除功能
		@RequestMapping(value="/deluser.json",method=RequestMethod.GET)
		@ResponseBody
		public Object deluser(@RequestParam String id){
			HashMap<String, String> resultMap = new HashMap<String, String>();
			if(StringUtils.isNullOrEmpty(id)){
				resultMap.put("delResult", "notexist");
			}else{
				try {
					if(devAppService.deleteAppInfoById(Integer.parseInt(id)))
						resultMap.put("delResult", "true");
					else
						resultMap.put("delResult", "false");
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return JSONArray.toJSONString(resultMap);
		}
		
		//修改
		@RequestMapping(value="/app/appinfomodify{id}",method=RequestMethod.GET)
		public String getUserById(@PathVariable String id,Model model,HttpServletRequest request){
			logger.debug("getProviderById id===================== "+id);
			AppInfo appInfo=new AppInfo();
			try {
				appInfo = devAppService.getAppInfoById(Integer.parseInt(id));
				if(appInfo.getLogoLocPath() != null && !"".equals(appInfo.getLogoLocPath())){
					String[] paths = appInfo.getLogoLocPath().split("\\"+File.separator);
					logger.debug("view picPath paths[paths.length-1]============ " + paths[paths.length-1]);
					appInfo.setLogoLocPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
				}
				if(appInfo.getLogoPicPath() != null && !"".equals(appInfo.getLogoPicPath())){
					String[] paths = appInfo.getLogoPicPath().split("\\"+File.separator);
					logger.debug("view workPicPath paths[paths.length-1]============ " + paths[paths.length-1]);
					appInfo.setLogoPicPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			model.addAttribute(appInfo);
			return "developer/appinfomodify";
		}
	
}
